package com.example.administrator.biyesheji_print.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.biyesheji_print.Adapter.PrintAdapter;
import com.example.administrator.biyesheji_print.Adapter.mPrintAdapter;
import com.example.administrator.biyesheji_print.Bean.FileInfo;
import com.example.administrator.biyesheji_print.Bean.PrintInfo;
import com.example.administrator.biyesheji_print.MainActivity;
import com.example.administrator.biyesheji_print.R;
import com.example.administrator.biyesheji_print.Utils.Constant;
import com.example.administrator.biyesheji_print.Utils.PathUtil;
import com.example.administrator.biyesheji_print.Utils.SharedPreferencesUtils;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

/**
 * Created by Administrator on 2018/3/28.
 */

public class PrintFragment extends Fragment {


    @BindView(R.id.iv_type)
    ImageView ivType;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    Unbinder unbinder;
    @BindView(R.id.bt_add)
    Button btAdd;
    private View view;
    private String type;
    private TextView tv_type;
    private TDialog tDialog;
    private mPrintAdapter printAdapter;
    private Realm realm;
    private ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
    private Realm realm1;

    @Nullable

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_print, null);
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        realm1 = Realm.getDefaultInstance();
        tv_type = view.findViewById(R.id.tv_type);
        unbinder = ButterKnife.bind(this, view);
        //Log.i("text","oncreateview");
        return view;
    }

    private void initView(View view) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        printAdapter = new mPrintAdapter(list,getContext(),this);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.setAdapter(printAdapter);

        printAdapter.setOnItemClickListener(new mPrintAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                ImageView iv_fileddelete = view.findViewById(R.id.iv_fileddelete);
                iv_fileddelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final RealmResults<FileInfo> all = realm.where(FileInfo.class).equalTo("position", position).findAll();
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                all.deleteAllFromRealm();
                                list.remove(position);
                                if (list.size()==0){
                                    HashMap<String, Object> map = new HashMap<>();
                                    map.put("filename","请选择文件");
                                    map.put("path","");
                                    map.put("type","");
                                    list.add(map);
                                }
                                printAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                });
            }
        });





    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode ==Activity.RESULT_OK&&requestCode==1){
            Uri uri = data.getData();
            final String path = new PathUtil().getPath(getContext(), uri);//filepath
            String[] split = path.split("/");
            final String filename=split[split.length-1];//filename
            final int position = SharedPreferencesUtils.getInt(getContext(), "position", 0);//sp读取点击位置
            TextView tv_file = recyclerview.getChildAt(position).findViewById(R.id.tv_file);
            final ImageView iv_fileselect = recyclerview.getChildAt(position).findViewById(R.id.iv_fileselect);
            final ImageView iv_fileddelete = recyclerview.getChildAt(position).findViewById(R.id.iv_fileddelete);
//            iv_fileselect.setVisibility(View.GONE);
//            iv_fileddelete.setVisibility(View.VISIBLE);
            if (list.size()!=0){
                for (int i=0;i<list.size();i++){
                    if (filename.equals(list.get(i).get("filename").toString())){
                        Toast.makeText(getContext(),"请重新选择文件，"+filename+"文件已存在",Toast.LENGTH_SHORT).show();
                        tv_file.setText("请选择文件");
                        break;
                    }
                    else{
                        list.get(position).put("filename",filename);
                        printAdapter.notifyDataSetChanged();
                        tv_file.setText(filename);
                        break;
                    }
            }
            }
            else {
                list.get(position).put("filename",filename);
                tv_file.setText(filename);
            }


            iv_fileddelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final RealmResults<FileInfo> all = realm.where(FileInfo.class).equalTo("position", position).findAll();
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            all.deleteAllFromRealm();
                            list.remove(position);
                            //RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();
                            printAdapter.notifyItemRemoved(position);
                        }
                    });
                }
            });
//            if (type.equals("")){
//                Toast.makeText(getContext(),"请选择类型",Toast.LENGTH_SHORT).show();
//            }
            realm.executeTransaction(new Realm.Transaction() {
                public void execute(Realm realm) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setFilepath(path);
                    fileInfo.setFilename(filename);
                    fileInfo.setPosition(position);
                    type = SharedPreferencesUtils.getStringValue(getContext(), Constant.TYPE, "");
                    Log.i("text",type+"result");
                    fileInfo.setType(type);
                    realm.copyToRealm(fileInfo);
                }
            });


            //strings.get(position).replace("请选择文件",filename);

          //  Log.i("text",tv_file.getText().toString());

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
        realm.close();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {//懒加载
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            type = SharedPreferencesUtils.getStringValue(getContext(), Constant.TYPE, "");
            Log.i("text",type+"type");
            tv_type.setText("打印类型-" + type);
            realm = Realm.getDefaultInstance();
            RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();
            if (all.size() != 0) {
                list.clear();
                for (int i = 0; i < all.size(); i++) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("filename", all.get(i).getFilename());
                    map.put("filepath", all.get(i).getFilepath());
                    map.put("position",all.get(i).getPosition());
                   // Log.i("text",all.get(i).getType()+"typefirst");
                    map.put("type",type);
                    list.add(map);
                    // mDocumenAdapter.notifyDataSetChanged();
//                    View childAt = recyclerview.getChildAt(all.get(i).getPosition());
//                    ImageView iv_fileddelete = childAt.findViewById(R.id.iv_fileddelete);
                }
            }
            else {
                if (list.size()==0){
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("filename","请选择文件");
                    map.put("path","");
                    map.put("type","");
                    list.add(map);
                }

            }
            initView(view);
        }

    }


    /**
     * 展示打印类型选择框
     */
    private void showTypeDialog() {
        tDialog = new TDialog.Builder(getFragmentManager())
                .setLayoutRes(R.layout.select_type_dialog)
                .setScreenHeightAspect(getActivity(), 0.23f)
                .setScreenWidthAspect(getActivity(), 0.8f)
                .setGravity(Gravity.CENTER)
                .setCancelable(true)
                .setCancelableOutside(true)
                .addOnClickListener(R.id.rb1, R.id.rb2, R.id.rb3)
                .setOnBindViewListener(new OnBindViewListener() {
                    public void bindView(BindViewHolder viewHolder) {
                        boolean black = SharedPreferencesUtils.getBoolean(getContext(), "black", false);
                        boolean color = SharedPreferencesUtils.getBoolean(getContext(), "color", false);
                        boolean photo = SharedPreferencesUtils.getBoolean(getContext(), "photo", false);
                        viewHolder.setChecked(R.id.rb1, black);
                        viewHolder.setChecked(R.id.rb2, color);
                        viewHolder.setChecked(R.id.rb3, photo);
                    }
                })
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.rb1:
                                SharedPreferencesUtils.putBoolean(getContext(), "black", true);
                                SharedPreferencesUtils.putBoolean(getContext(), "color", false);
                                SharedPreferencesUtils.putBoolean(getContext(), "photo", false);
                                SharedPreferencesUtils.putStringValue(getContext(), Constant.TYPE,"黑白打印");
                                tv_type.setText("打印类型-黑白打印");
                                realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();
                                        for (int i=0;i<all.size();i++){
                                            all.get(i).setType("黑白打印");
                                        }
                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.rb2:
                                SharedPreferencesUtils.putBoolean(getContext(), "color", true);
                                SharedPreferencesUtils.putBoolean(getContext(), "black", false);
                                SharedPreferencesUtils.putBoolean(getContext(), "photo", false);
                                SharedPreferencesUtils.putStringValue(getContext(), Constant.TYPE,"彩色打印");
                                tv_type.setText("打印类型-彩色打印");
                                realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();
                                        for (int i=0;i<all.size();i++){
                                            all.get(i).setType("彩色打印");
                                        }
                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.rb3:
                                SharedPreferencesUtils.putBoolean(getContext(), "photo", true);
                                SharedPreferencesUtils.putBoolean(getContext(), "black", false);
                                SharedPreferencesUtils.putBoolean(getContext(), "color", false);
                                SharedPreferencesUtils.putStringValue(getContext(), Constant.TYPE,"照片打印");
                                tv_type.setText("打印类型-照片打印");
                                realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();
                                        for (int i=0;i<all.size();i++){
                                            all.get(i).setType("照片打印");
                                        }
                                    }
                                });
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_type, R.id.bt_submit, R.id.bt_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_type:
                showTypeDialog();
                break;
            case R.id.bt_submit:
              //  Log.i("text1",tv_type.getText().toString());
                final RealmResults<FileInfo> all = realm.where(FileInfo.class).findAll();//当前打印列表的文件信息
                final RealmResults<PrintInfo> all1 = realm1.where(PrintInfo.class).findAll();//文档列表中的文件信息
                        if (tv_type.getText().toString().equals("打印类型-")){
                            Toast.makeText(getContext(),"请选择打印类型",Toast.LENGTH_SHORT).show();
                        }
                        else if (all.size()==0){
                            Toast.makeText(getContext(),"请选择文件",Toast.LENGTH_SHORT).show();
                        }
                        else{
                            for (int i=0;i<all.size();i++){
                                final int finalI = i;
                                if (all.get(i).getFilename().contains(".png")&&tv_type.getText().toString().equals("打印类型-黑白打印")){
                                    Toast.makeText(getContext(),"类型不正确",Toast.LENGTH_SHORT).show();
                                    break;
                                }
                                if (all.get(i).getFilename().contains(".doc")&&tv_type.getText().toString().equals("打印类型-照片打印")){
                                    Toast.makeText(getContext(),"类型不正确",Toast.LENGTH_SHORT).show();
                                    break;
                                }
                                if (all.get(i).getFilename().contains(".docx")&&tv_type.getText().toString().equals("打印类型-照片打印")){
                                    Toast.makeText(getContext(),"类型不正确",Toast.LENGTH_SHORT).show();
                                    break;
                                }
                                if (all.get(i).getFilename().contains(".txt")&&tv_type.getText().toString().equals("打印类型-照片打印")){
                                    Toast.makeText(getContext(),"类型不正确",Toast.LENGTH_SHORT).show();
                                    break;
                                }

                                if (all1.size()!=0){
                                    for (int j=0;j<all1.size();j++){
//                                        Log.i("text",all1.get(j).getFilepath());
//                                        Log.i("text",all.get(finalI).getFilepath());
//                                        Log.i("text",all1.get(j).getType());
//                                        Log.i("text",all.get(finalI).getType());

                                        if (all1.get(j).getFilepath().equals(all.get(finalI).getFilepath())&&all1.get(j).getType().equals(all.get(finalI).getType())){
                                            Toast.makeText(getContext(),"文件重复："+all1.get(j).getFilename(),Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            realm1.executeTransaction(new Realm.Transaction() {
                                                public void execute(Realm realm) {
                                                    PrintInfo printInfo = new PrintInfo();
                                                    printInfo.setFilepath(all.get(finalI).getFilepath());
                                                    printInfo.setFilename(all.get(finalI).getFilename());
                                                    printInfo.setPosition(all.get(finalI).getPosition());
                                                    // Log.i("text",all.get(finalI).getType()+"type");
                                                    type = SharedPreferencesUtils.getStringValue(getContext(), Constant.TYPE, "");
                                                    printInfo.setType(type);
                                                    realm.copyToRealm(printInfo);

                                                }
                                            });
                                            break;
                                        }
                                }


                                }
                                else{
                                    realm1.executeTransaction(new Realm.Transaction() {
                                        public void execute(Realm realm) {
                                            PrintInfo printInfo = new PrintInfo();
                                            printInfo.setFilepath(all.get(finalI).getFilepath());
                                            printInfo.setFilename(all.get(finalI).getFilename());
                                            printInfo.setPosition(all.get(finalI).getPosition());
                                            // Log.i("text",all.get(finalI).getType()+"type");
                                            type = SharedPreferencesUtils.getStringValue(getContext(), Constant.TYPE, "");
                                            printInfo.setType(type);
                                            realm.copyToRealm(printInfo);
                                        }
                                    });
                                }

                            }
                            final RealmResults<FileInfo> all2 = realm.where(FileInfo.class).findAll();
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    all2.deleteAllFromRealm();
                                    list.clear();
                                    printAdapter.notifyDataSetChanged();
                                }
                            });
                            SharedPreferencesUtils.putStringValue(getContext(), Constant.TYPE,"");
                            SharedPreferencesUtils.putBoolean(getContext(), "color", false);
                            SharedPreferencesUtils.putBoolean(getContext(), "black", false);
                            SharedPreferencesUtils.putBoolean(getContext(), "photo", false);
                            // Log.i("text",all1.toString());
                            MainActivity.tabhost.setCurrentTab(2);
                        }


                break;
            case R.id.bt_add:

                if (list.get(list.size()-1).get("filename")!="请选择文件"){
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("filename","请选择文件");
                    map.put("path","");
                    list.add(map);
                    printAdapter.notifyItemInserted(list.size()-1);
                }

                break;
        }
    }
}
